package com.rrjjg.app.core.utils;

import com.rrjjg.app.core.exception.RjException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Set;
import java.util.stream.Collectors;

import static com.rrjjg.app.core.Constants.SEMICOLON;
import static com.rrjjg.app.core.exception.MsgEnum.PARAM_ERR;


/**
 * ----------------------------------------------------------------------------- <br>
 * 功能 :  <br>
 *  
 * 授权 : (C) Copyright (c) 2022 <br>
 * ----------------------------------------------------------------------------- <br>
 * 作者 : Vayne <br>
 * 时间 : 2022/8/24 9:38 <br>
 */
public abstract class ValidationUtil {

    static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public ValidationUtil() {
    }

    /* 默认验证方法 */
    public static <T> void validation(T t) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<T>> set = validator.validate(t);
        appendMsg(set);
    }


    /* 根据分组验证异常*/
    public static <T> void validation(T t, Class<?>... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<T>> set = validator.validate(t, groups);
        appendMsg(set);
    }

    /* 拼接请求参数异常方法 */
    private static <T> void appendMsg(Set<ConstraintViolation<T>> set) {
        if (set.size() > 0) {
            String errMsg = set.stream().map(v -> v.getMessage()).collect(Collectors.joining(SEMICOLON));
            throw new RjException(errMsg,PARAM_ERR.getCode());
        }
    }

    public static interface add{}

    public static interface update{}

    public static interface del{}
}
